/*
 * @Description: flowLine
 * @Author: ljt
 * @Date: 2022-12-29 15:35
 * @LastEditTime: 2022-12-29 15:35
 * @LastEditors: ljt
 */

import * as Cesium from "cesium";

type Data = {
    position: number[],
    title: string,
    id: string
}
export default function addDynamicLabel(
    viewer: Cesium.Viewer,
    data: Data,
    type: boolean = true,
    style: {[props: string]: string} = {}
){
	let div = document.createElement("div");
    div.id = data.id;
    const styleInt = {
        position: "absolute",
        width: "100px",
        height: "30px",
        'font-size':  "23px",
        'line-height':  "150px",
        'text-indent': '85px',
        color:  type ? "#FFD03B" : "#19FCDE"
    }
    const styleList = {...styleInt, ...style}
    for(const i in styleList){
        div.style[i] = styleList[i]
    }
    const url = type ?  new URL('@/assets/index/burHotPoint.png', import.meta.url).href : new URL('@/assets/index/staHotPoint.png', import.meta.url).href
    div.innerHTML = `
		<div style="width: 260px; height: 260px;background:url(${url}) no-repeat center center/contain" >${data.title}</div>
    `;
    viewer.cesiumWidget.container.appendChild(div);
    let gisPosition = Cesium.Cartesian3.fromDegrees(
        data.position[0],
        data.position[1],
        0
    );
    //实时更新位置
    viewer.scene.postRender.addEventListener(() => {
	    const canvasHeight = viewer.scene.canvas.height;
	    const windowPosition = new Cesium.Cartesian2();
	    Cesium.SceneTransforms.wgs84ToWindowCoordinates(
	        viewer.scene,
	        gisPosition,
	        windowPosition
	    );
	    div.style.bottom = canvasHeight - windowPosition.y + "px";
	    const elWidth = div.offsetWidth;
	    div.style.left = windowPosition.x - elWidth / 2 + "px";

		//解决滚动不隐藏问题
		const camerPosition = viewer.camera.position;
            let height = viewer.scene.globe.ellipsoid.cartesianToCartographic(camerPosition).height;
            height += viewer.scene.globe.ellipsoid.maximumRadius;
            // console.log(camerPosition, val.position )
            if((!(Cesium.Cartesian3.distance(camerPosition,gisPosition ) > height))&&viewer.camera.positionCartographic.height<50000000){
                div.style.display = "block"
            }else{
                div.style.display = "none"
            }
            // @ts-ignore
    }, this);
}